package com.guducat.collegeWeb.service;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;

import com.guducat.collegeWeb.dto.request.LoginDTO;
import com.guducat.collegeWeb.dto.response.UserInfoDTO;
import com.guducat.collegeWeb.entity.User;
import com.guducat.collegeWeb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;

import java.util.List;

@Service
public class UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 用户登录
     * @param loginDTO 登录信息
     * @return 用户信息
     */
    public UserInfoDTO login(LoginDTO loginDTO) {
        // 查询用户
        User user = userMapper.findByUsername(loginDTO.getUsername());

        // 计算输入密码的MD5值
        String inputPasswordMd5 = SaSecureUtil.md5(loginDTO.getPassword());

        // 用户不存在或密码错误
        if (user == null || !inputPasswordMd5.equals(user.getPassword())) {
            // 输出详细的登录失败调试信息
            System.out.println("=== 登录失败调试信息 ===");
            System.out.println("登录时间: " + java.time.LocalDateTime.now());
            System.out.println("尝试登录用户名: " + loginDTO.getUsername());
            System.out.println("原始密码: " + loginDTO.getPassword());
            System.out.println("输入密码MD5: " + inputPasswordMd5);

            if (user == null) {
                System.out.println("用户查询结果: 用户不存在");
            } else {
                System.out.println("用户查询结果: 用户存在");
                System.out.println("用户ID: " + user.getId());
                System.out.println("用户名: " + user.getUsername());
                System.out.println("数据库密码: " + user.getPassword());
                System.out.println("密码匹配结果: " + inputPasswordMd5.equals(user.getPassword()));
                System.out.println("用户状态: " + user.getStatus());
                System.out.println("用户权限: " + user.getPermission());
            }

            // 额外的SHA256对比（用于调试）
            String inputPasswordSha256 = SaSecureUtil.sha256(loginDTO.getPassword());
            String expectedSha256 = "240BE518FABD2724DDB6F04EEB1DA5967448D7E831C08C8FA822809F74C720A9";
            System.out.println("输入密码SHA256: " + inputPasswordSha256.toUpperCase());
            System.out.println("期望SHA256: " + expectedSha256);
            System.out.println("SHA256匹配: " + inputPasswordSha256.toUpperCase().equals(expectedSha256));
            System.out.println("========================");

            return null;
        }

        // 输出登录成功调试信息
        System.out.println("=== 登录成功调试信息 ===");
        System.out.println("登录时间: " + java.time.LocalDateTime.now());
        System.out.println("登录用户名: " + loginDTO.getUsername());
        System.out.println("用户ID: " + user.getId());
        System.out.println("用户昵称: " + user.getNickname());
        System.out.println("密码验证: 成功");
        System.out.println("========================");

        // 获取用户IP地址
        String ipAddress = getClientIpAddress();

        // 更新用户最后登录IP
        userMapper.updateLastLoginIp(user.getId(), ipAddress);

        // 登录成功，使用Sa-Token记录用户登录状态
        StpUtil.login(user.getId());

        // 获取用户权限列表（通过StpInterface实现类自动获取）
        List<String> permissionList = StpUtil.getPermissionList();

        // 返回用户信息
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setId(user.getId());
        userInfoDTO.setUsername(user.getUsername());
        userInfoDTO.setNickname(user.getNickname());
        userInfoDTO.setAvatar(user.getAvatar());
        userInfoDTO.setRole(0); // 保留字段，兼容旧版本
        userInfoDTO.setPermissions(permissionList);
        userInfoDTO.setToken(StpUtil.getTokenValue());
        userInfoDTO.setLastLoginIp(ipAddress);

        return userInfoDTO;
    }

    /**
     * 获取客户端IP地址
     * @return IP地址
     */
    private String getClientIpAddress() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String ip = request.getHeader("X-Forwarded-For");

            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }

            return ip;
        }

        return "未知IP";
    }

    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    public UserInfoDTO getCurrentUserInfo() {
        // 检查是否已登录
        if (!StpUtil.isLogin()) {
            return null;
        }

        // 获取当前登录用户ID
        Integer userId = StpUtil.getLoginIdAsInt();

        // 查询用户信息
        User user = userMapper.findById(userId);
        if (user == null) {
            return null;
        }

        // 获取用户权限列表（通过StpInterface实现类自动获取）
        List<String> permissionList = StpUtil.getPermissionList();

        // 返回用户信息
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        userInfoDTO.setId(user.getId());
        userInfoDTO.setUsername(user.getUsername());
        userInfoDTO.setNickname(user.getNickname());
        userInfoDTO.setAvatar(user.getAvatar());
        userInfoDTO.setRole(0); // 保留字段，兼容旧版本
        userInfoDTO.setPermissions(permissionList);
        userInfoDTO.setLastLoginIp(user.getLastLoginIp());

        return userInfoDTO;
    }

    /**
     * 检查用户是否为管理员
     * @return 是否为管理员
     */
    public boolean isAdmin() {
        // 检查是否已登录
        if (!StpUtil.isLogin()) {
            return false;
        }

        // 使用Sa-Token的权限验证
        return StpUtil.hasPermission("Admin");
    }

    /**
     * 用户注销
     */
    public void logout() {
        StpUtil.logout();
    }


}
